package com.pengpai.pangucms.service.impl;

import com.pengpai.pangucms.entity.SysFileinfo;
import com.pengpai.pangucms.mapper.SysFileinfoMapper;
import com.pengpai.pangucms.service.ISysFileinfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengpai.pangucms.utils.UserUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wushuai
 * @since 2023-08-29
 */
@Service
public class SysFileinfoServiceImpl extends ServiceImpl<SysFileinfoMapper, SysFileinfo> implements ISysFileinfoService {

    @Resource
    private SysFileinfoMapper sysFileinfoMapper;
    @Value("${pangu.upload.static}")
    private String uploadPath;

    public String upload(MultipartFile file, boolean isAttach) {
        SysFileinfo sysFileinfo = new SysFileinfo();
        if(isAttach) sysFileinfo.setIsAttach(1);
        sysFileinfo.setFileName(file.getOriginalFilename());
        sysFileinfo.setFileSize(file.getSize());
        String uuid = String.valueOf(UUID.randomUUID());
        sysFileinfo.setFileCode(uuid);
        String rootPath = uploadPath;
        File directory  = new File(rootPath);
        if(!directory.exists()){
            directory.mkdirs();
        }
        String suff = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        sysFileinfo.setFileSuff(suff);
        sysFileinfo.setVisitUrl("/files/" +  uuid + suff);
        String path = rootPath  + uuid + suff;// 绝对路径地址
        sysFileinfo.setFilePath(path);
        File uploadpath = new File(path);
        try {
            file.transferTo(uploadpath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        sysFileinfo.setUploadUser(UserUtils.CurrentUserName());
        sysFileinfo.setUploadTime(LocalDateTime.now());
        sysFileinfoMapper.insert(sysFileinfo);
        return uuid;
    }

}
